package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.ProductCriteria;
import com.leo.ibatis.demo.dao.ProductDao;
import com.leo.ibatis.demo.domain.Product;
import com.leo.ibatis.demo.util.Paging;

public class ProductDaoImpl extends SqlMapClientDaoSupport implements ProductDao {

	public void insert(Product product) throws DataAccessException {
		getSqlMapClientTemplate().insert("Product.insert", product);
	}

	public int update(Product product) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Product.update", product, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String productid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Product.delete", productid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Product select(String productid) throws DataAccessException {
		return (Product) getSqlMapClientTemplate().queryForObject("Product.select", productid);
	}

	@SuppressWarnings("unchecked")
	public List<Product> list(ProductCriteria productCriteria) throws DataAccessException {
		Assert.notNull(productCriteria, "productCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Product.list", productCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Product> listOnPage(ProductCriteria productCriteria) throws DataAccessException {
		Assert.notNull(productCriteria, "productCriteria must not be null");
		Assert.notNull(productCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(productCriteria);
		Paging paging = productCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Product.list", productCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(ProductCriteria productCriteria) throws DataAccessException {
		Assert.notNull(productCriteria, "productCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Product.count", productCriteria)).intValue();
	}

}
